package com.czr.dao.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czr.dao.entity.CzrAbout;
import com.czr.dao.entity.CzrBusi;
import com.czr.dao.entity.CzrUser;
import com.czr.dao.mapper.CzrAboutMapper;
import com.czr.util.*;
import com.czr.vo.*;
import com.czr.dao.mapper.CzrUserMapper;
import com.czr.dao.service.CzrUserService;
import com.czr.dto.Search;
import com.czr.dto.VerifyParam;
import com.czr.dto.WxParam;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 */
@Service
public class CzrUserServiceImpl extends ServiceImpl<CzrUserMapper, CzrUser> implements CzrUserService {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    public CzrUserMapper czrUserMapper;

    @Autowired
    public CzrAboutMapper czrAboutMapper;


    @Override
    public Result<Map<String, Object>> login(String username, String password, Integer isLoginType) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
        //账号登录
        Map<String, Object> map = czrUserMapper.getLogin(username, password);
        //手机号码登录
        Map<String, Object> map1 = czrUserMapper.getLoginPhone(username, password);
        if (!StringUtils.isEmpty(map)) {
            if (isLoginType == 3) {
                JwtUtil.EXPIRE_TIME = 720;
                String token = JwtUtil.createToken(map.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);

                CzrUser czrUser = new CzrUser();
                czrUser.setLoginDate(format.format(new Date()));
                if (!StringUtils.isEmpty(map.get("login_date"))) {
                    czrUser.setOldLoginTime(map.get("login_date").toString());
                }
                czrUser.setId(Long.parseLong(map.get("id").toString()));
                czrUser.updateById();
                return Result.data(200, dataMap, "登录成功");
            } else {
                if (StringUtils.isEmpty(isLoginType)) {
                    isLoginType = 0;
                }
                JwtUtil.EXPIRE_TIME = 24;
                String token = JwtUtil.createToken(map.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                CzrUser czrUser = new CzrUser();
                czrUser.setLoginDate(format.format(new Date()));
                if (!StringUtils.isEmpty(map.get("login_date"))) {
                    czrUser.setOldLoginTime(map.get("login_date").toString());
                }
                czrUser.setId(Long.parseLong(map.get("id").toString()));
                czrUser.updateById();
                return Result.data(200, dataMap, "登录成功");
            }

        } else if (!StringUtils.isEmpty(map1)) {
            if (isLoginType == 3) {
                JwtUtil.EXPIRE_TIME = 720;
                String token = JwtUtil.createToken(map1.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map1.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map1), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                CzrUser czrUser = new CzrUser();
                czrUser.setLoginDate(format.format(new Date()));
                if (!StringUtils.isEmpty(map1.get("login_date"))) {
                    czrUser.setOldLoginTime(map1.get("login_date").toString());
                }
                czrUser.setId(Long.parseLong(map1.get("id").toString()));
                czrUser.updateById();
                return Result.data(200, dataMap, "登录成功");
            } else {
                if (StringUtils.isEmpty(isLoginType)) {
                    isLoginType = 0;
                }
                JwtUtil.EXPIRE_TIME = 24;
                String token = JwtUtil.createToken(map1.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map1.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map1), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                CzrUser czrUser = new CzrUser();
                czrUser.setLoginDate(format.format(new Date()));
                if (!StringUtils.isEmpty(map1.get("login_date"))) {
                    czrUser.setOldLoginTime(map1.get("login_date").toString());
                }
                czrUser.setId(Long.parseLong(map1.get("id").toString()));
                czrUser.updateById();
                return Result.data(200, dataMap, "登录成功");
            }
        } else {
            return Result.success(201, "账号或密码错误！");
        }
    }

    @Override
    public Result<Map<String, Object>> adminLogin(String username, String password, Integer isLoginType) throws Exception {
        ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
        //账号登录
        Map<String, Object> map = czrUserMapper.getLoginAdmin(username, password);
        //手机号码登录
        Map<String, Object> map1 = czrUserMapper.getLoginPhoneAdmin(username, password);
        if (!StringUtils.isEmpty(map)) {
            if (isLoginType == 3) {
                JwtUtil.EXPIRE_TIME = 720;
                String token = JwtUtil.createToken(map.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                return Result.data(200, dataMap, "登录成功");
            } else {
                if (StringUtils.isEmpty(isLoginType)) {
                    isLoginType = 0;
                }
                JwtUtil.EXPIRE_TIME = 24;
                String token = JwtUtil.createToken(map.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                return Result.data(200, dataMap, "登录成功");
            }

        } else if (!StringUtils.isEmpty(map1)) {
            if (isLoginType == 3) {
                JwtUtil.EXPIRE_TIME = 720;
                String token = JwtUtil.createToken(map1.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map1.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map1), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                return Result.data(200, dataMap, "登录成功");
            } else {
                if (StringUtils.isEmpty(isLoginType)) {
                    isLoginType = 0;
                }
                JwtUtil.EXPIRE_TIME = 24;
                String token = JwtUtil.createToken(map1.get("id").toString(), username);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("token", token);
                map1.put("isLoginType", isLoginType);
                valueOperations.set(token, JSONObject.toJSONString(map1), JwtUtil.EXPIRE_TIME + 1, TimeUnit.HOURS);
                return Result.data(200, dataMap, "登录成功");
            }
        } else {
            return Result.success(201, "账号或密码错误！");
        }
    }

    @Override
    public Result<Object> getUserInfo(Integer userId) throws Exception {
        TencentCosUtil tencentCosUtil = new TencentCosUtil();
        CzrUser czrUser = this.getById(userId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!StringUtils.isEmpty(czrUser.getBirthDate())) {
            czrUser.setBirthDate(format.format(format.parse(czrUser.getBirthDate())));
        }
//        if (!StringUtils.isEmpty(czrUser.getComingDate())) {
//            czrUser.setComingDate(format.format(format.parse(czrUser.getComingDate())));
//        }
        if (!StringUtils.isEmpty(czrUser.getOldLoginTime())) {
            czrUser.setOldLoginTime(format1.format(format1.parse(czrUser.getOldLoginTime())));
        }
        CzrUserResultVo czrUserResultVo = new CzrUserResultVo();
        BeanUtils.copyProperties(czrUser, czrUserResultVo);
        if (!StringUtils.isEmpty(czrUserResultVo.getUserLogo())) {
            czrUserResultVo.setUserLogo(czrUserResultVo.getUserLogo());
        }
        return Result.data(200, czrUserResultVo, "");
    }

    @Override
    public Result<Map<String, Object>> register(CzrUser czrUser) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //验证账号是否存在
        Map<String, Object> map = czrUserMapper.getUserName(czrUser.getUsername());
        if (!StringUtils.isEmpty(map)) {
            return Result.success(201, "账号已存在，请确认后重新输入！");
        }
        //验证手机号是否存在
        Map<String, Object> map1 = czrUserMapper.getPhone(czrUser.getPhone());
        if (!StringUtils.isEmpty(map1)) {
            return Result.success(201, "手机号码已存在，请确认后重新输入！");
        }
//        czrUser.setUserLevel(0);
//        czrUser.setUserType(0);
        czrUser.setStatus(1);
        czrUser.setUSort(98);
        czrUser.setPassword(Md5.md52(czrUser.getPassword()));
        czrUser.setUuid(UUID.randomUUID().toString());
        czrUser.setInsertTime(format.format(new Date()));
        boolean resultBoolean = czrUser.insert();
        if (resultBoolean) {
            return Result.success(200, "注册成功！");
        } else {
            return Result.success(201, "注册失败！");
        }
    }

    @Override
    public Result<Object> list(Search search) throws Exception {
        TencentCosUtil tencentCosUtil = new TencentCosUtil();
        Page<CzrUser> page = new Page<>();
        page.setSize(search.getSize());
        page.setCurrent(search.getCurrent());
        LambdaQueryWrapper<CzrUser> ew = new LambdaQueryWrapper<>();
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(search.getKeyword())) {
            ew.like(CzrUser::getUnit, search.getKeyword()).or().like(CzrUser::getName, search.getKeyword());
        }
//        ew.eq(CzrUser::getUserType, 0);
//        ew.eq(CzrUser::getStatus, 1);
        ew.in(CzrUser::getUIdentity, Arrays.asList(1, 2));
        ew.orderByAsc(CzrUser::getUSort).orderByDesc(CzrUser::getInsertTime);
        page = this.getBaseMapper().selectPage(page, ew);
        JSONArray array = new JSONArray();
        for (CzrUser czrUser : page.getRecords()) {
            MenberListVo menberListVO = new MenberListVo();
            BeanUtils.copyProperties(czrUser, menberListVO);
            if (!StringUtils.isEmpty(menberListVO.getUserLogo())) {
                menberListVO.setUserLogo(menberListVO.getUserLogo());
            }
            array.add(menberListVO);
        }
        JSONObject object = PageUtil.getPage(array, page);
        return Result.data(object);
    }

    @Override
    public Result<Map<String, Object>> update(CzrUser czrUser) throws Exception {
        //验证用户id是否存在
        Map<String, Object> map = czrUserMapper.getUserInfo(czrUser.getId());
        if(!StringUtils.isEmpty(czrUser.getUserLogo())){
            if(czrUser.getUserLogo().contains("https")){
             int p=czrUser.getUserLogo().lastIndexOf("com");
             int s=czrUser.getUserLogo().lastIndexOf("/");
             czrUser.setUserLogo(czrUser.getUserLogo().substring(p+4,s));
            }
        }

        if (StringUtils.isEmpty(map)) {
            return Result.fail("用户ID无效，请检查！");
        }
        int r = czrUserMapper.updateById(czrUser);
        if (r >= 0) {
            return Result.success(200, "资料修改成功！");
        } else {
            return Result.success(201, "资料修改失败！");
        }
    }
    @Override
    public Result<Map<String, Object>> deladmin(Integer userId) throws Exception {
        //验证用户id是否存在
//        Map<String, Object> map = czrUserMapper.getUserInfo(Long.parseLong(String.valueOf(userId)));

        CzrUser czrUser=czrUserMapper.selectById(userId);
        if (StringUtils.isEmpty(czrUser)) {
            return Result.fail("用户ID无效，请检查！");
        }
        czrUser.setStatus(-1);
        int r = czrUserMapper.updateById(czrUser);
        if (r >= 0) {
            return Result.success(200, "删除成功！");
        } else {
            return Result.success(201, "删除失败！");
        }
    }

    @Override
    public Result<Map<String, Object>> updatePwd(CzrUserVo czrUserVo) throws Exception {
        //验证用户id是否存在
        CzrUser czrUser1 = this.getById(czrUserVo.getId());
        if (StringUtils.isEmpty(czrUser1)) {
            return Result.success(201, "用户ID无效，请检查！");
        }
        String mPwd = Md5.md52(czrUserVo.getPassword());
        String oldmPwd = Md5.md52(czrUserVo.getOldPassword());
        if (!czrUser1.getPassword().equals(oldmPwd)) {
            return Result.success(201, "原密码不正确，请检查后输入！");
        }
        CzrUser czrUser = new CzrUser();
        czrUser.setId(czrUserVo.getId());
        czrUser.setPassword(mPwd);
        int r = czrUserMapper.updateById(czrUser);
        if (r >= 0) {
            return Result.success(200, "修改密码成功！");
        } else {
            return Result.success(201, "修改密码失败！");
        }
    }

    @Override
    public Result<Map<String, Object>> updateAdminPwd(Integer userId,String password ,JSONObject cacheToken) throws Exception {
        if (cacheToken.getInteger("user_type") != 1) {
            return Result.success(201, "非管理员账号，无法重置密码！");
        }
        //验证用户id是否存在
        CzrUser czrUser1 = this.getById(userId);
        if (StringUtils.isEmpty(czrUser1)) {
            return Result.success(201, "用户ID无效，请检查！");
        }
        String mPwd = Md5.md52(password);
        CzrUser czrUser = new CzrUser();
        czrUser.setId(Long.valueOf(userId));
        czrUser.setPassword(mPwd);
        int r = czrUserMapper.updateById(czrUser);
        if (r >= 0) {
            return Result.success(200, "重置密码成功！");
        } else {
            return Result.success(201, "重置密码失败！");
        }
    }



    protected Log log = LogFactory.getLog(this.getClass());



    @Override
    public Result<Object> about_select() throws Exception {
        CzrAbout czrAbout = czrAboutMapper.selectById(1);
        return Result.data(200, czrAbout, "");
    }

    @Override
    public Result<Object> about_update(String content) throws Exception {
        if(StringUtils.isEmpty(content)){
            return Result.success(201, "内容不能为空！");
        }
        JSONObject jsonObject=JSONObject.parseObject(content);
        CzrAbout czrAbout = new CzrAbout();
        czrAbout.setContent(jsonObject.getString("content"));
        czrAbout.setId(Long.parseLong("1"));
        int c=czrAboutMapper.updateById(czrAbout);
        if (c>=0) {
            return Result.success(200, "修改成功！");
        } else {
            return Result.success(201, "修改失败！");
        }
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString());
    }
}
